package com.example.fw;

import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.Select;

import java.util.LinkedList;
import java.util.List;

import static com.example.fw.RandomHelper.getRnd;

/**
 * Created with IntelliJ IDEA.
 * User: pshevchenko
 * Date: 06.03.13
 * Time: 19:03
 * To change this template use File | Settings | File Templates.
 */
public abstract class WebDriverHelperBase extends HelperBase {

    private boolean isElementPresent(By by) {
        try {
            driver.findElement(by);
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }

    private String closeAlertAndGetItsText() {
        try {
            Alert alert = driver.switchTo().alert();
            if (acceptNextAlert) {
                alert.accept();
            } else {
                alert.dismiss();
            }
            return alert.getText();
        } finally {
            acceptNextAlert = true;
        }
    }

    protected boolean acceptNextAlert = true;
    protected WebDriver driver;

    protected void fillTextField(By locator, String keys) {
        if ((keys != null)&&(!keys.equals("null"))){
            driver.findElement(locator).clear();
            driver.findElement(locator).sendKeys(keys);
        }
    }

    protected void selectComboByText(By locator, String text) {
        if ((text != null)&&(!text.equals("null")))
            new Select(driver.findElement(locator)).selectByVisibleText(text);
    }

    protected void clickElement(By locator) {
        driver.findElement(locator).click();
    }

    protected String getFieldValue(By locator) {
        WebElement field = driver.findElement(locator);
        String result = field.getAttribute("value");
        return result;
    }

    protected String getFieldText(By locator) {
        WebElement field = driver.findElement(locator);
        String result = field.getText();
        return result;
    }
    protected String getFieldAttribute(By locator, String attributeName) {
        WebElement field = driver.findElement(locator);
        String result = field.getAttribute(attributeName);
        return result;
    }

    protected List<String> getDropDownList(String listName){
        List<String> resultList = new LinkedList<String>();
        List<WebElement> optionsList = driver.findElements(By.xpath("//select[@name=\"" + listName + "\"]/option"));
        /*for (int i = 0; i < optionsList.size(); i ++)
            resultList.add(optionsList.get(i).getText());*/
        for (WebElement option : optionsList){
            resultList.add(option.getText());
        }
        return resultList;
    }

    protected WebDriverHelperBase(ApplicationManager manager) {
        super(manager);
        this.driver = manager.getDriver();
    }

    public int getRandomIndex(int groupCount) {
        return getRnd().nextInt(groupCount - 1);
    }
}